<template>
    <div class="info-box">
        <div class="title">商户信息</div>
        <el-form
            class="form-box"
            ref="enterpriseInfoRef"
            v-loading="loading"
            :element-loading-text="loadingText"
            :model="formInfo"
            :rules="rules"
            :inline="false"
            scroll-to-error
            :disabled="props.disabled"
            label-position="top"
            label-width="auto">
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="营业执照图片" prop="corp_license">
                        <div class="upload-img-box">
                            <ZwUnityKitCertificateUpload
                                v-model="formInfo.corp_license"
                                :imageList="corp_license_url"
                                :disabled="props.disabled"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                ocrType="LICENSE"
                                @submit="onUploadOCR"
                                :multiple="false"
                                uploadLabel="上传营业执照"
                                uploadTips="上传营业执照后自动识别信息，支持JPG、BMP、PNG格式，图片大小不能超过1M。"
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M"
                                @start="onStartLoading"
                                @finished="onFinishedLoading" />
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="商户名称" prop="corp_name">
                        <template #label>
                            <div class="label">商户名称<span>（与营业执照保持一致）</span></div>
                        </template>
                        <el-input
                            v-model.trim="formInfo.corp_name"
                            placeholder="请输入商户名称"
                            type="text"
                            maxlength="32"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="商户简称" prop="corp_abbreviation">
                        <template #label>
                            <div class="label">商户简称<span>（在支付页面展示给消费者）</span></div>
                        </template>
                        <el-input
                            v-model.trim="formInfo.corp_abbreviation"
                            placeholder="请输入商户简称，商家自定义"
                            type="text"
                            maxlength="8"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="统一社会信用代码" prop="corp_unified_social_credit_code">
                        <el-input
                            v-model.trim="formInfo.corp_unified_social_credit_code"
                            placeholder="请输入统一社会信用代码"
                            type="text"
                            maxlength="18"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="注册地区" prop="corp_reg_area">
                        <ZwUnityKitCascader v-model="formInfo.corp_reg_area" placeholder="请选择注册地区" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="注册地址" prop="corp_reg_address">
                        <template #label>
                            <div class="label">注册地址<span>（与营业执照上一致）</span></div>
                        </template>
                        <el-input
                            v-model.trim="formInfo.corp_reg_address"
                            placeholder="请输入注册地址"
                            type="text"
                            maxlength="64"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="营业期限" prop="corp_times">
                        <ZwUnityKitDatePicker
                            v-model="formInfo.corp_times"
                            v-model:isLongTerm="formInfo.corp_license_is_long" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="经营类目" prop="corp_category">
                        <ZwUnityKitCascader
                            v-model="formInfo.corp_category"
                            placeholder="请选择经营类目"
                            type="category"
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="所属行业" prop="corp_industry">
                        <ZwUnityKitProfessionSelect
                            v-model="formInfo.corp_industry"
                            v-model:name="formInfo.corp_industry_name" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="注册资本" prop="corp_capital" v-if="formInfo.corp_main_type == 1">
                        <ZwUnityKitInputNumber v-model="formInfo.corp_capital" />
                    </el-form-item>
                    <el-form-item label="组成形式" prop="corp_composition" v-if="formInfo.corp_main_type == 2">
                        <el-select v-model="formInfo.corp_composition" placeholder="请选择组成形式" clearable>
                            <el-option
                                v-for="item in options"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 暂时注释隐藏 -->
            <!-- <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="公司网站名称" prop="corp_site_name">
                        <el-input
                            v-model.trim="formInfo.corp_site_name"
                            placeholder="请输入公司网站名称"
                            type="text"
                            maxlength="32"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="ICP备案号" prop="corp_icp_number">
                        <el-input
                            v-model.trim="formInfo.corp_icp_number"
                            placeholder="请输入ICP备案号"
                            type="text"
                            maxlength="16"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
            </el-row> -->
            <el-row :gutter="60">
                <el-col :span="8">
                    <el-form-item label="经营范围" prop="corp_scope">
                        <template #label>
                            <div class="label">经营范围<span>（参照营业执照）</span></div>
                        </template>
                        <el-input
                            v-model.trim="formInfo.corp_scope"
                            :rows="5"
                            placeholder="请输入经营范围"
                            type="textarea"
                            maxlength="128"
                            show-word-limit
                            clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="营业场所照片（需上传2张）" prop="corp_license_place">
                        <div class="upload-img-box upload-img-box-left">
                            <ZwUnityKitCertificateUpload
                                class="corp-license-place-box-left"
                                v-model="formInfo.corp_license_place[0]"
                                :imageList="corpLicenseUrl"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                :limitNum="1"
                                :disabled="props.disabled"
                                :multiple="false"
                                uploadLabel="上传营业场所照片"
                                uploadTips="支持JPG、BMP、PNG格式，图片大小不能超过1M"
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M" />
                        </div>
                        <div class="upload-img-box">
                            <ZwUnityKitCertificateUpload
                                v-model="formInfo.corp_license_place[1]"
                                :imageList="corpLicenseUrlTwo"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                :limitNum="1"
                                :disabled="props.disabled"
                                :multiple="false"
                                uploadLabel="上传营业场所照片"
                                uploadTips=""
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M" />
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="门头照" prop="corp_door">
                        <div class="upload-img-box">
                            <ZwUnityKitCertificateUpload
                                v-model="formInfo.corp_door"
                                :imageList="corp_door_url"
                                :disabled="props.disabled"
                                :limitFormat="['JPG', 'JPEG', 'BMP', 'PNG']"
                                :multiple="false"
                                uploadLabel="上传门头照"
                                uploadTips="支持JPG、BMP、PNG格式，图片大小不能超过1M。"
                                validateTips="仅支持上传JPG、BMP、PNG格式的图片，图片大小不能超过1M" />
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>
<script setup>
import { ref, reactive, computed, watch } from 'vue';

import { packSelectObjUtil } from '@/commons/utils';
import constants from '@/commons/constants';

const emit = defineEmits(['update:modelValue', 'ocrChange']);

const options = reactive(packSelectObjUtil(constants.COMPOSITION_FORM));

const props = defineProps({
    modelValue: {
        type: Object,
        default: () => {}
    },
    disabled: {
        type: Boolean,
        default: false
    }
});

const formInfo = computed({
    get() {
        return props.modelValue;
    },
    set(val) {
        emit('update:modelValue', val);
    }
});

const corp_license_url = reactive({
    code: '',
    url: ''
});

const corpLicenseUrl = reactive({
    code: '',
    url: ''
});

const corpLicenseUrlTwo = reactive({
    code: '',
    url: ''
});

const corp_door_url = reactive({
    code: '',
    url: ''
});

const enterpriseInfoRef = ref(null);

const loading = ref(false);
const loadingText = ref('');

// const formInfo = reactive({});

const checkCorpTimes = (ruls, value = [], callback) => {
    // console.log(value,'value');
    if (!value[0] || !value[1]) {
        return callback(new Error('请选择营业期限'));
    }
    if (new Date(value[0]).getTime() - new Date(value[1]).getTime() >= 0) {
        return callback(new Error('结束时间需要大于开始时间'));
    }
    if (new Date(value[1]).getTime() - new Date().getTime() < 60 * 24 * 60 * 60 * 1000) {
        return callback(new Error('结束时间距当前时间需超过60天'));
    }
    callback();
};

const checkCorpLicensePlace = (ruls, value = [], callback) => {
    if (!value?.filter(el => el).length) {
        return callback(new Error('请上传营业场所照片'));
    } else if (value?.filter(el => el).length < 2) {
        return callback(new Error('请上传两张营业场所照片'));
    }

    callback();
};

const rules = reactive({
    corp_license: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
    corp_name: [
        { required: true, message: '请输入商户名称', trigger: 'blur' },
        { pattern: /^.{5,32}/, message: '商户名称最少5个字符', trigger: 'blur' }
    ],
    corp_abbreviation: [
        { required: true, message: '请输入商户简称', trigger: 'blur' },
        { pattern: /^.{2,8}/, message: '商户简称最少2个字符', trigger: 'blur' }
    ],
    corp_unified_social_credit_code: [
        { required: true, message: '请输入统一社会信用代码', trigger: 'blur' },
        { pattern: /^[0-9A-Z]{18}$/, message: '请输入正确的统一社会信用代码', trigger: 'blur' }
    ],
    corp_reg_area: [{ required: true, message: '请选择注册地区', trigger: 'change' }],
    corp_reg_address: [{ required: true, message: '请输入注册地址', trigger: 'blur' }],
    corp_times: [{ required: true, validator: checkCorpTimes, trigger: 'change' }],
    corp_category: [{ required: true, message: '请选择经营类目', trigger: 'change' }],
    corp_industry: [{ required: true, message: '请选择所属行业', trigger: 'change' }],
    corp_scope: [{ required: true, message: '请输入经营范围', trigger: 'blur' }],
    corp_site_name: [{ required: true, message: '请输入公司网站名称', trigger: 'blur' }],
    corp_icp_number: [{ required: true, message: '请输入ICP备案号', trigger: 'blur' }],
    corp_capital: [{ required: true, message: '请输入注册资本', trigger: 'blur' }],
    corp_composition: [{ required: true, message: '请选择组成形式', trigger: 'change' }],
    corp_license_place: [{ required: true, validator: checkCorpLicensePlace, trigger: 'change' }],
    corp_door: [{ required: true, message: '请上传门头照', trigger: 'change' }]
});

/**
 * 表单校验
 * @param {*} typeList 需要校验的字段，默认全校验
 */
const validate = async (typeList = []) => {
    if (typeList.length) {
        let errNum = 0;
        for (let i = 0; i < typeList?.length; i++) {
            try {
                await enterpriseInfoRef.value?.validateField(typeList[i]);
            } catch (err) {
                errNum++;
            }
        }
        return !errNum;
    } else {
        return await enterpriseInfoRef.value?.validate();
    }
};

/**
 * 营业执照ocr识别
 */
const onUploadOCR = (val = {}) => {
    let info = val || {};
    emit('ocrChange', info);
    enterpriseInfoRef.value?.clearValidate('corp_license');
    if (!formInfo.value.corp_name && info.companyName) {
        formInfo.value.corp_name = info.companyName;
        enterpriseInfoRef.value?.clearValidate('corp_name');
    }
    if (!formInfo.value.corp_unified_social_credit_code && info.creditCode) {
        formInfo.value.corp_unified_social_credit_code = info.creditCode;
        enterpriseInfoRef.value?.clearValidate('corp_unified_social_credit_code');
    }
    if (!formInfo.value.corp_reg_area && info.area) {
        formInfo.value.corp_reg_area = info.area;
        enterpriseInfoRef.value?.clearValidate('corp_reg_area');
    }
    if (!formInfo.value.corp_reg_address && info.businessAddress) {
        formInfo.value.corp_reg_address = info.businessAddress;
        enterpriseInfoRef.value?.clearValidate('corp_reg_address');
    }
    if (!formInfo.value.corp_scope && info.businessScope) {
        formInfo.value.corp_scope = info.businessScope?.substr(0, 128);
        enterpriseInfoRef.value?.clearValidate('corp_scope');
    }
    if (!formInfo.value.corp_times.length || formInfo.value.corp_times.filter(ite => ite).length < 2) {
        try {
            let list = info.validPeriod?.split('至') || [];
            if (list.length == 2) {
                let startTime = list[0].replace(/年|月/g, '-').replace(/日/g, '');
                let endTime = list[1].replace(/年|月/g, '-').replace(/日/g, '');
                formInfo.value.corp_times[0] = startTime;
                if (['不约定期限', '长期'].includes(list[1])) {
                    formInfo.value.corp_license_is_long = 1;
                } else if (endTime) {
                    formInfo.value.corp_times[1] = endTime;
                }
            }
        } catch {}
        enterpriseInfoRef.value?.clearValidate('corp_times');
    }
};

const onStartLoading = () => {
    loading.value = true;
    loadingText.value = '正在识别...';
};

const onFinishedLoading = () => {
    loading.value = false;
    loadingText.value = '';
};

watch(
    () => formInfo.value.corp_license_place,
    val => {
        if (val && val.length == 2) {
            enterpriseInfoRef.value?.clearValidate('corp_license_place');
        }
    },
    { deep: true }
);

watch(
    () => formInfo.value.corp_door,
    (val, oldVal) => {
        if (!oldVal && val) {
            enterpriseInfoRef.value?.clearValidate('corp_door');
        }
    }
);

watch(
    () => formInfo.value?.corp_license_url,
    val => {
        if (val) {
            corp_license_url.code = formInfo.value.corp_license;
            corp_license_url.url = formInfo.value.corp_license_url;
        }
    }
);

watch(
    () => formInfo.value?.corp_license_place_url,
    val => {
        if (val && val[0]) {
            corpLicenseUrl.code = formInfo.value?.corp_license_place[0];
            corpLicenseUrl.url = formInfo.value?.corp_license_place_url[0];
        }
        if (val && val[1]) {
            corpLicenseUrlTwo.code = formInfo.value?.corp_license_place[1];
            corpLicenseUrlTwo.url = formInfo.value?.corp_license_place_url[1];
        }
    }
);

watch(
    () => formInfo.value?.corp_door_url,
    val => {
        if (val) {
            corp_door_url.code = formInfo.value.corp_door;
            corp_door_url.url = formInfo.value.corp_door_url;
        }
    }
);

defineExpose({
    validate
});
</script>
<style lang="scss" scoped>
.el-form-item {
    margin-bottom: 24px;
}
.info-box {
    margin-bottom: 16px;
    background: #ffffff;
    .title {
        padding: 16px 24px;
        font-size: 16px;
        color: #333333;
        line-height: 24px;
        border-bottom: 1px solid #e9e9e9;
    }
    .form-box {
        margin: 24px 24px 0;
        .label {
            display: inline-block;
            span {
                font-size: 14px;
                color: rgba(153, 153, 153, 0.85);
                line-height: 22px;
            }
        }
        .upload-img-box {
            width: 45%;
            margin-bottom: 24px;
        }
        .upload-img-box-left {
            margin-right: 16px;
        }
        .corp-license-place-box {
            width: 100%;
            // display: flex;
            // align-items: flex-start;
            // .corp-license-place-box-left {
            //     margin-right: 16px;
            // }
        }
        .upload-tips {
            margin-top: 8px;
            font-size: 12px;
            color: #999;
            line-height: 1.6;
        }
    }
}
</style>
